<html>
<head>

<title>Groovy Goodness: Use the set Method to Define a Date or Calendar Value</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Use the set Method to Define a Date or Calendar Value</h3>

<div class="post">
<p>In a previous post we learned about the new subscript operator support in Groovy 1.7.3 for setting <code>Date</code> or <code>Calendar</code> values. But we have other new ways in Groovy 1.7.3: we can use a <code>set()</code> method to set the values. The method accepts a <code>Map</code> with the following keys: year, month, date, hourOfDay, minute and second. The keys are used to set the according values of the <code>Date</code> or <code>Calendar</code> object.</p>
<pre class="brush:groovy">
import static java.util.Calendar.*

def cal = Calendar.instance
cal.set(year: 2010, month: JULY, date: 9)

assert 'Birthday @ 2010-7-9' == 'Birthday @ ' + cal.format('yyyy-M-d')
assert FRIDAY == cal[DAY_OF_WEEK]

def date = new Date()
date.set(hourOfDay: 12, minute: 0, second: 0, year: 2010, month: JUNE, date: 1)

assert '12:00:00' == date.format('HH:mm:ss')
assert 2010 == date[YEAR]
assert JUNE == date[MONTH]
assert 1 == date.getAt(DATE)
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>